package com.fyl.pattern.proxy.jdk_proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 获取代理对象的工厂类
 */
public class ProxyFactory {
    //声明目标对象
    private TrainStation trainStation = new TrainStation();

    public SellTickets getProxyObject(){
        /**
         * ClassLoader loader,目标对象类加载器 用于加载代理类
         *Class<?>[] interfaces, 代理类实现的接口的字节码对象
         *InvocationHandler h 代理对象的调用处理程序
         */
        SellTickets proxyObject = (SellTickets) Proxy.newProxyInstance(
                TrainStation.class.getClassLoader(),
                TrainStation.class.getInterfaces(),
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//                        System.out.println("invoke方法执行了");
                        System.out.println("代售点收取一定的服务费用(jdk代理)");
                        //执行目标对象的方法
                        Object invoke = method.invoke(trainStation, args);
                        return invoke;
                    }
                }
        );
                return proxyObject;
    }
}
